$(function () {
    layui.use(['laydate', 'laytpl', 'table', 'form', 'formSelects', 'layer', 'util', 'soulTable','locals'], function () {
        var laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            form = layui.form,
            formSelects = layui.formSelects,
            layer = layui.layer,
            util = layui.util,
            soulTable = layui.soulTable,
            locals = layui.locals;
        form.render();
        var pageName = getPageName();
        var localParam = locals.get(pageName);
        var areaArr = [], timer = null, tbIndex = null,allAreas = [] ,allMeters = [];
        var max = util.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss');
        var param = {};
        var datetype = {type: 'date', format: 'yyyy-MM-dd'};

        initAll();
        function initAll() {
            getAllAreas();
        }

        function initDate(repType, dateObj) {
            laydate.render({
                elem: "#startTime",
                value: dateObj.st,
                type: datetype.type,
                format: datetype.format,
                trigger: 'click',
                max: max,
                done: function(value){
                    $('#startTime').val(value);
                    param.dateObj.st = value;
                    locals.set(pageName, param);
                    $(".refreshBtn").click();
                }
            });
            laydate.render({
                elem: "#endTime",
                value: dateObj.et,
                type: datetype.type,
                format: datetype.format,
                trigger: 'click',
                max: max,
                done: function(value){
                    var stime = $('#startTime').val();
                    var gap = new Date(value).getTime() - new Date(stime).getTime();
                    if(gap < 0){
                        layer.alert('结束时间应大于开始时间');
                    }else{
                        param.dateObj.et = value;
                        locals.set(pageName, param);
                        $(".refreshBtn").click();
                    }
                }
            });
        }

        function getAllAreas() {
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allAreas = result;
                        var getTpl = $('#area-tpl').html();
                        laytpl(getTpl).render(result, function (html) {
                            $('.areaMenu').html(html);
                            formSelects.render('areaMenu');
                            formSelects.btns('areaMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('areaMenu', 'val');
                            getAllMeters();
                        });
                    }
                }
            });
        }

        function getAllMeters() {
            $.ajax({
                type: "GET",
                url: ctx + "/report/getAllMeters.do",
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        allMeters = result;
                        var getTpl = $('#meter-tpl').html();
                        laytpl(getTpl).render(result, function (html) {
                            $('.meterMenu').html(html);
                            formSelects.render('meterMenu');
                            formSelects.btns('meterMenu', ['select', 'remove','reverse'], {show: 'name', space: '10px'});
                            formSelects.value('meterMenu', 'val');
                        });
                        assignValue();
                    }
                }
            });
        }

        // 给筛选条件赋值
        function assignValue(){
            // 判断是否有缓存
            if(localParam){ // 有缓存
                param.dateObj = Object.assign({}, localParam.dateObj);
                param.area = localParam.area;
                param.meter = localParam.meter;
            }else{ // 无缓存，初始化
                param.dateObj = Object.assign({}, {
                    'st': util.toDateString(new Date(), 'yyyy-MM') + '-01', // 开始
                    'et': util.toDateString(new Date(), 'yyyy-MM-dd') // 结束
                });
                param.area = allAreas.map(function(item){
                    return item.areaId
                });
                param.meter = allMeters.map(function(item){
                    return item.meterCode
                });
                // 存
                locals.set(pageName, param);
            }
            // 赋值
            initDate(param.repType, param.dateObj);
            formSelects.value('areaMenu', param.area);
            formSelects.value('meterMenu', param.meter);
            $(".refreshBtn").click();
        }

        function filterMeters(areaArr) {
            var list = [], meters = [];
            allMeters.forEach(function(item){
                areaArr.forEach(function(val){
                    if(item.areaId == val){
                        meters.push(item.meterCode);
                        list.push({"name": item.areaName, "type": "optgroup"});
                        list.push({"name": item.deviceName + '_' + item.anotherName, "value": item.meterCode});
                    }
                });
            });
            formSelects.data('meterMenu', 'local', {
                arr: uniqObjInArray(list)
            });
            formSelects.value('meterMenu', meters);
            param.area = [].concat(areaArr);
            param.meter = [].concat(meters);
            locals.set(pageName, param);
            $(".refreshBtn").click();
        }

        // 监听区域多选
        formSelects.on('areaMenu', function(id, vals, val, isAdd, isDisabled){
            areaArr.length = [];
            areaArr = vals.map(function(item){
                return item.value
            });
            filterMeters(areaArr);
        }, true);

        // 监听设备多选
        formSelects.on('meterMenu', function(id, vals, val, isAdd, isDisabled){
            param.meter = [].concat(vals.map(function(item){
                return item.value
            }));
            locals.set(pageName, param);
            $(".refreshBtn").click();
        }, true);

        //点击刷新
        $('.searchBtn').click(function () {
            $(".refreshBtn").click();
        });
        $(".refreshBtn").click(function () {
            form.on('submit(search)', function (data) {
                getAllTypeMsg(data.field);
                return false;
            });
        });

        // 点击左侧，展示右侧记录
        $('.wrap').on('click', function () {
            $(this).toggleClass('open-up');
            $(this).find('.msg-list').toggleClass('layui-hide');
            return false; // 阻止冒泡捕获
        });

        // 查询所有类型的消息记录
        // 1报警灯， 2微信， 3简讯， 4客服
        function getAllTypeMsg(datas) {
            var resData = {
                1: [{recTime: '2020-10-10 10:00:00', content: '设备1超标', isSend: '推送成功'},{recTime: '2020-10-10 20:00:00', content: '设备1超标', isSend: '推送失败'},{recTime: '2020-10-11 10:00:00', content: '设备2超标', isSend: '推送成功'}],
                2: [{recTime: '2020-10-10 10:00:00', content: '设备3超标', isSend: '推送成功'},{recTime: '2020-10-11 10:00:00', content: '设备4超标', isSend: '推送成功'}],
                3: [],
                4: [{recTime: '2020-10-10 10:00:00', content: '设备7超标', isSend: '推送成功'}]
            };
            var msgData = {};
            for(var key in resData){
                var len = Math.ceil(resData[key].length / 2);
                msgData[key] = [resData[key].slice(0, len)];
                if(resData[key].length > 1){
                    msgData[key].push(resData[key].slice(len));
                }
            }
            // console.log(msgData);
            var getTpl = $('#msg-table-tpl').html();
            laytpl(getTpl).render(msgData[1], function (html) {
                $('.alarmLight .msg-list').html(html);
            });
            laytpl(getTpl).render(msgData[2], function (html) {
                $('.WeChat .msg-list').html(html);
            });
            laytpl(getTpl).render(msgData[3], function (html) {
                $('.SMS .msg-list').html(html);
            });
            laytpl(getTpl).render(msgData[4], function (html) {
                $('.customerService .msg-list').html(html);
            });

            // $.ajax({
            //     type: "POST",
            //     url: ctx + "/",
            //     data: datas,
            //     dataType: "json",
            //     success: function (result) {
            //         if (result.data) {
            //
            //         } else if (result.message) {
            //             layer.alert(result.message);
            //         }
            //     }
            // });
        }

        /*报警灯*/
        $('.light-btn').click(function () {
            layer.open({
                type: 1,
                title: "报警灯",
                closeBtn: 1,
                anim: 0,
                area: '800px',
                content: $('#light-tpl').html(),
                success: function () {
                    form.render();
                    renderTable();
                }
            });
            return false; // 阻止冒泡捕获
        });

        form.on('submit(alarmLight-add)', function (res) {
            // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
            return false;
        });

        function renderTable() {
            var data = [
                {lightId: 1, lightName:'一楼报警灯', meters:'01_测试110,02_办公室1'},
                {lightId: 2, lightName:'二楼报警灯',meters:'03_客户端1,04_测试2,05_隔壁水表'}
            ];
            table.render({
                elem: '#lightList',
                data: data,
                title: '报警灯信息表',
                defaultToolbar: [],
                cols: [[
                    {field: 'lightId', title: '报警灯编号',width:100}
                    , {field: 'lightName', title: '报警灯位置'}
                    , {field: 'meters', title: '已绑定设备'}
                    , {fixed: 'right', title: '操作', width: 200, templet: '#light-tools-tpl'}
                ]],
                page: {
                    layout: ['prev', 'page', 'next', 'count']
                    , limit: 10  //每页显示条数
                },
                loading: true
            });
        }

        table.on('tool(lightList)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit-light'){
                var layerIdx = layer.open({
                    type: 1,
                    title: "修改报警灯",
                    closeBtn: 1,
                    anim: 0,
                    area: 'auto',
                    content: $('#light-edit-tpl').html()
                });
                form.val("alarmLight-edit", data);
                form.on('submit(alarmLight-edit)', function (res) {
                    // console.log(res.field);
                    updateLight(res.field,obj,layerIdx);
                    return false;
                });
                $(".alarmLight-edit button[type='cancel']").click(function () {
                    layer.close(layerIdx);
                    return false;
                });
            }else if(obj.event === 'bind-device'){
                var layerIdx = layer.open({
                    type: 1,
                    title: "【" + data.lightName + "】绑定设备",
                    closeBtn: 1,
                    anim: 0,
                    area: '600px',
                    content: $('#binding-tpl').html(),
                    success: function (layero) {
                        var nameArr = data.meters.split(',');
                        var devs = '';
                        allMeters.forEach(function (item) {
                            var mname = item.deviceName + '_' + item.anotherName;
                            if(nameArr.indexOf(mname) == -1 ){
                                devs += '<input type="checkbox" name="meters" value="'+item.meterCode+'" title="'+ mname +'" lay-skin="primary">'
                            }else{
                                devs += '<input type="checkbox" name="meters" value="'+item.meterCode+'" title="'+ mname +'" lay-skin="primary" checked>'
                            }
                        });
                        layero.find('.devlist').html(devs);
                        form.render();
                    }
                });
                form.on('submit(bind-dev)', function (res) {
                    var valueArr = [],valueName = [];
                    $('input[name="meters"]:checked').each(function () {
                        valueArr.push($(this).val());
                        valueName.push($(this).attr('title'));
                    });
                    var field = {
                        lightId: data.lightId,
                        meterCode: valueArr.join(',')
                    };
                    // console.log(field);
                    bindDevice(field,valueName,obj,layerIdx);
                    return false;
                });
            } else if(obj.event === 'del'){
                layer.confirm('确定删除？', function(index){
                    deleteLight(obj,index);
                });
            }
        });

        // 全选 反选 清空
        util.event('lay-active', {
            checkAll: function(){
                $('.devlist input[name="meters"]').prop("checked", true);
                form.render('checkbox');
            }
            ,checkClear: function(){
                $('.devlist input[name="meters"]').prop("checked", false);
                form.render('checkbox');
            }
            ,checkReverse: function(){
                var checkedArr = [];
                $('.devlist input[name="meters"]:checked').each(function(){
                    checkedArr.push($(this).val());
                });
                $('.devlist input[name="meters"]').each(function () {
                    if(checkedArr.indexOf($(this).val()) == -1){
                        $(this).prop('checked',true);
                    }else{
                        $(this).prop('checked',false);
                    }
                });
                form.render('checkbox');
            }
        });

        // 更新报警灯
        function updateLight(parm,obj,index){
            $.ajax({
                type: "POST",
                url: ctx + "/",
                dataType: "json",
                data: parm,
                success: function (res) {
                    if (res.code == '000000'){
                        //同步更新缓存对应的值
                        obj.update(parm);
                        layer.close(index);
                    }else{
                        layer.alert(res.message)
                    }
                }
            });
        }

        // 删除报警灯
        function deleteLight(obj,index){
            $.ajax({
                type: "GET",
                url: ctx + "/",
                dataType: "json",
                success: function (res) {
                    if (res.code == '000000'){
                        obj.del();
                        layer.close(index);
                    }else{
                        layer.alert(res.message)
                    }
                }
            });
        }

        // 绑定设备
        function bindDevice(field,valueName,obj,index){
            $.ajax({
                type: "POST",
                url: ctx + "/",
                dataType: "json",
                data: field,
                success: function (res) {
                    if (res.code == '000000'){
                        //同步更新缓存对应的值
                        obj.update({
                            meters: valueName.join(',')
                        });
                        layer.close(index);
                    }else{
                        layer.alert(res.message)
                    }
                }
            });
        }

        /* 微信 */
        $('.wechat-btn').click(function () {
            layer.open({
                type: 1,
                title: "微信",
                closeBtn: 1,
                anim: 0,
                area: '500px',
                content: $('#wechat-tpl').html()
            });
            return false;
        });

        /* 简讯 */
        $('.sms-btn').click(function () {
            layer.open({
                type: 1,
                title: "简讯",
                closeBtn: 1,
                anim: 0,
                area: '500px',
                content: $('#sms-tpl').html(),
                success: function(layero){
                    getPhoneList();
                }
            });
            return false;
        });

        form.on('submit(sms-param)', function (res) {
            var val = res.field.phoneNumber.replace(/，/ig,','); // 中文逗号替换为英文逗号,
            var numArr = val.split(',');
            var phoneReg= /^[1][3,4,5,7,8][0-9]{9}$/ ; // 校验手机号格式
            var flag = true;
            numArr.forEach(function(v){
                if(!phoneReg.test(v)){
                    flag = false;
                    layer.alert(v + '该号码格式错误' );
                    return false;
                }
            });
            if(flag){
                addPhone(val,numArr);
            }
            return false;
        });

        // 绑定设备
        function addPhone(field,numArr){
            // $.ajax({
            //     type: "POST",
            //     url: ctx + "/",
            //     dataType: "json",
            //     data: field,
            //     success: function (res) {
            //         if (res.code == '000000'){
            //             showPhoneList(numArr);
            //         }else{
            //             layer.alert(res.message);
            //         }
            //     }
            // });
        }

        function getPhoneList(){
            $('.phone-list').html('');
            var list = ['18312341234','13798765432'];
            showPhoneList(list);
            // $.ajax({
            //     type: "GET",
            //     url: ctx + "/",
            //     dataType: "json",
            //     data: field,
            //     success: function (res) {
            //         if (res.code == '000000'){
            //
            //         }else{
            //             layer.alert(res.message);
            //         }
            //     }
            // });
        }

        function showPhoneList(numArr){
            var str = '';
            numArr.forEach(function(item){
                str += '<span><em>'+ item +'</em><i class="layui-icon layui-icon-close" title="删除"></i></span>'
            });
            $('.phone-list').append(str);
        }

        $('body').on('click','.phone-list .layui-icon-close',function(){
            var num = $(this).prev('em').text();
            var elm = $(this).parent('span');
            delPhoneList(num, elm);
        });

        function delPhoneList(num,elm){
            $.ajax({
                type: "GET",
                url: ctx + "/",
                dataType: "json",
                data: {
                    phoneNum: num
                },
                success: function (res) {
                    if (res.code == '000000'){
                        elm.remove();
                    }else{
                        layer.alert(res.message);
                    }
                }
            });
        }

        /* 客服平台 */
        $('.customer-btn').click(function(){
            layer.open({
                type: 1,
                title: "客服平台",
                closeBtn: 1,
                anim: 0,
                area: '500px',
                content: $('#customer-tpl').html(),
                success: function(layero){
                    layero.find('textarea').val('/messageManage/list');
                }
            });
            return false;
        });

        $('body').on('click','#copy',function(){
            $('#txt').select(); // 选中文本
            document.execCommand("Copy"); // 执行复制
            layer.tips('已复制','#tip',{
                tips: [2, '#555']
            });
        });

        // 导出excel
        // $('.exportBtn').click(function () {
        //     soulTable.export('myTable', {filename: $(".title").text() + '.xlsx'});
        // });

        // 打印
        // $('.printBtn').click(function () {
        //     createPrintTable();
        //     // 创建iframe，填入需要打印的内容和样式
        //     var iframe = document.createElement('IFRAME'),
        //         doc = null,
        //         style = ["<style>", "body{font-size: 12px; color: #000;}",
        //             "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
        //             "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
        //             "thead tr th:first-child,tbody tr td:first-child{width:80px}",
        //             "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
        //         printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
        //         ptitle = $('<div class="ptitle">' + $('#printcontent .title').text() + '</div>');
        //     iframe.setAttribute("id", "print-iframe");
        //     iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
        //     document.body.appendChild(iframe);
        //     doc = iframe.contentWindow.document;
        //     printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
        //     printHtml.find("th.layui-table-patch").remove();
        //     printHtml.find(".layui-table-col-special").remove();
        //     doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
        //     iframe.contentWindow.focus();
        //     iframe.contentWindow.print();
        //     iframe.remove();
        //     $('#printContentBox').empty();
        // });
        //
        // function createPrintTable() {
        //     $('#printContentBox').html('<table id="printTb"></table>');
        //     var temp = tbIndex.config;
        //     // 所有数据加载为新表格
        //     table.render({
        //         elem: '#printTb'
        //         , data: temp.data
        //         , cellMinWidth: 48
        //         , size: 'sm'
        //         , defaultToolbar: []
        //         , cols: temp.cols
        //         , limit: temp.data.length
        //     })
        // }
    });
});
